<template>
  <t-dialog v-model:visible="model" header="添加批次" :confirm-loading="confirmPending" confirm-btn="添加" @close="handleClose" @confirm="handleConfirm">
    <t-form ref="dialogForm" :data="batchFormData" :rules="formRules">
      <t-form-item label="渠道(公司)" name="companyId">
        <t-select v-model="batchFormData.companyId" filterable placeholder="请选择渠道" :loading="channelLoading" :options="channelOptions" @search="handleChannelSearch" />
      </t-form-item>
      <t-form-item label="票类" name="ticketId">
        <t-select v-model="batchFormData.ticketId" filterable placeholder="请选择票类" :options="ticketOptions" :loading="ticketSearchPending" @search="handleTicketSearch" />
      </t-form-item>
      <t-form-item label="批次类型" name="batchType">
        <t-select v-model="batchFormData.batchType" placeholder="请选择批次类型">
          <t-option v-for="item in BatchType" :key="item" :label="batchTypeDict[item]" :value="item" />
        </t-select>
      </t-form-item>
      <t-form-item label="购票数量" name="ticketCount">
        <t-input-number v-model="batchFormData.ticketCount" placeholder="请输入购票数量" suffix="张" :allow-input-over-limit="false" :step="1" :min="1" :max="99999999" />
      </t-form-item>
      <t-form-item label="赠票数量" name="ticketCountGift">
        <t-input-number v-model="batchFormData.ticketCountGift" placeholder="请输入赠票数量" suffix="张" :allow-input-over-limit="false" :step="1" :min="0" :max="99999999" />
      </t-form-item>
    </t-form>
  </t-dialog>
</template>
<script setup lang="ts">
import type { FormInstanceFunctions, FormRules } from 'tdesign-vue-next'
import { MessagePlugin } from 'tdesign-vue-next'
import { reactive, ref, useTemplateRef } from 'vue'

import { createBatch } from '@/api/batch'
import { getChannelDetail, getChannelPageList } from '@/api/channel'
import type { BatchReqData } from '@/api/model/batch'
import { BatchType } from '@/api/model/batch'
import { EnabledStatus } from '@/api/model/common'
import { getTicketDetail, getTicketPageList } from '@/api/ticket'
import useSearchSelect from '@/hooks/selectSearch'
import { batchTypeDict } from '@/utils/dict/batch'

export type BatchFormDialogData = BatchReqData
const { companyId = '' } = defineProps<{
  companyId?: string
}>()
const emits = defineEmits<{
  (e: 'success'): void
}>()
const model = defineModel('visible', { type: Boolean })
const batchFormData = reactive<BatchFormDialogData>({
  companyId,
  batchType: BatchType.DIGITAL,
  ticketCount: 0,
  ticketCountGift: 0,
  ticketId: '',
})

const formRules: FormRules<BatchFormDialogData> = {
  companyId: [{ required: true, message: '请选择渠道', type: 'error' }],
  ticketId: [{ required: true, message: '请选择票类', type: 'error' }],
  batchType: [{ required: true, message: '请选择批次类型', type: 'error' }],
  ticketCount: [{ required: true, message: '请输入购票数量', type: 'error' }],
  ticketCountGift: [{ required: true, message: '请输入赠票数量', type: 'error' }],
}

const { selectOptions: channelOptions, searchLoading: channelLoading, handleSearch: handleChannelSearch } = useSearchSelect(() => batchFormData.companyId, async (companyId) => {
  const channelDetail = await getChannelDetail(companyId)
  return {
    label: channelDetail.companyName,
    value: channelDetail.id,
  }
}, async (_value) => {
  const channelList = await getChannelPageList({ page: 1, size: 100, companyName: _value, enabled: EnabledStatus.ENABLED })
  return channelList.data.map(item => ({ label: item.companyName, value: item.id }))
})

const { selectOptions: ticketOptions, searchLoading: ticketSearchPending, handleSearch: handleTicketSearch } = useSearchSelect(() => batchFormData.ticketId, async (ticketId) => {
  const res = await getTicketDetail(ticketId)
  return ({ label: res.ticketName, value: res.id })
}, async (_query) => {
  const res = await getTicketPageList({ page: 1, size: 100, ticketName: _query, enabled: EnabledStatus.ENABLED })
  return res.data.map(item => ({ label: item.ticketName, value: item.id }))
})

const dialogForm = useTemplateRef<FormInstanceFunctions<BatchFormDialogData>>('dialogForm')
const confirmPending = ref(false)
function handleConfirm() {
  dialogForm.value?.validate().then((validateResult) => {
    if (validateResult === true) {
      confirmPending.value = true
      createBatch(batchFormData).then(() => {
        confirmPending.value = false
        model.value = false
        MessagePlugin.success('创建成功')
        emits('success')
      })
    }
  })
}

function handleClose() {

}
</script>
<style scoped>
:deep(.t-input-number) {
  width: 100%;
}
</style>
